/*
 * @(#)DmsSendEmailAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.contact.bean.ContactPerson;
import com.dcivision.contact.bean.MtmContactListObjectLink;
import com.dcivision.contact.dao.ContactPersonDAObject;
import com.dcivision.contact.dao.MtmContactListObjectLinkDAObject;
import com.dcivision.dms.EmailAuditTrailConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.bean.DmsSendEmail;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.user.dao.UserRecordDAObject;

/**
 * <p>Class Name:       DmsSendEmailAction.java    </p>
 * <p>Description:      The action class for DmsSendEmail.jsp</p>
 *
 *  @author          Wong Yam Lee
 *  @company         DCIVision Limited
 *  @creation date   10/09/2003
 *  @version         $Revision: 1.26.2.2 $
 */
public class DmsSendEmailAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.26.2.2 $";
  
  private static final String MESSAGE_SEND_SUCCESSFUL = "dms.label.email_sent";
  private static final String MESSAGE_SEND_FAILED = "dms.label.email_failed";

  /**
   *  Constructor - Creates a new instance of DmsSendEmailAction
   */
  public DmsSendEmailAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return null;
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return null;
  }

  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    Connection conn = this.getConnection(request);
    SessionContainer sessionCon = this.getSessionContainer(request);
    
    DmsSendEmailForm mailForm = (DmsSendEmailForm)form;
    String opMode = mailForm.getOpMode();
    
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionCon, conn);
    DmsDocument document = docRetrievalManager.getDocument(new Integer(request.getParameter("documentID")));
    request.setAttribute("docName", document.getDocumentName());
    
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionCon, conn);

    DmsValidation validation = docValidateManager.validateOperateAction(document, false, "L");
    List lstIdMisRight = validation.getLstIdReject();
    List lstIdBeLocked = validation.getLstIdlocked();
    List lstIdBeDeleted = validation.getLstIdDeleted();
    List lstIdBeArchived = validation.getLstIdArchived();
    if (!lstIdMisRight.isEmpty() ||
        !lstIdBeDeleted.isEmpty() ||
        !lstIdBeArchived.isEmpty()){
      for (int i=0; i<lstIdMisRight.size(); i++) {
        this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
      }
      for (int i=0; i<lstIdBeLocked.size(); i++) {
        this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
      }
      for (int i=0; i<lstIdBeDeleted.size(); i++) {
        this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
      }
      for (int i=0; i<lstIdBeArchived.size(); i++) {
        this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
      }
      if (isError(request)) {
        if (GlobalConstant.OP_MODE_INSERT.equals(opMode)){
          addError(request, MESSAGE_SEND_FAILED);
        }
        mailForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
      }
    }
    
    try{
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
        try {
          this.insertRecord(mapping, mailForm, request, response);
          this.commit(request);
          addMessage(request, MESSAGE_SEND_SUCCESSFUL);
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          addError(request, MESSAGE_SEND_FAILED);
          mailForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        } else {
          request.setAttribute(GlobalConstant.ACTION_MODE,GlobalConstant.NAV_MODE_VIEW);
          mailForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      }else{
        return super.execute(mapping,form,request,response);
      }
    }catch (ApplicationException ex) {
      handleApplicationException(request, ex);
      return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
    }   
  }
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    
    Connection conn = null;
    SessionContainer sessionCon = null;
    DocumentRetrievalManager docRetrievalManager = null;
    try{
      conn = this.getConnection(request);
      sessionCon = this.getSessionContainer(request);
      docRetrievalManager = new DocumentRetrievalManager(sessionCon, conn);
      
      DmsSendEmailForm mailForm = (DmsSendEmailForm)form;
      DmsSendEmail email = (DmsSendEmail)mailForm.getFormData();

      //  get all the recipients.
      String recipients=this.getExtraRecipients(mailForm,request);
      if(mailForm.getRecipients()!=null || mailForm.getRecipients()!=""){
    	  recipients = mailForm.getRecipients()+";"+this.getExtraRecipients(mailForm,request);
      }
      email.setRecipients(recipients);
      
      DmsDocument document = docRetrievalManager.getDocument(new Integer(request.getParameter("documentID")));
      String locationPath = docRetrievalManager.getLocationPath(document.getParentID())+"\\"+document.getDocumentName();
      String version = request.getParameter("version");
      request.setAttribute("docName", document.getDocumentName());
      
      DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionCon, conn);
      
      String postfix = docRetrievalManager.getPostfixByDocument(document);
      document.setDocumentName(document.getDocumentName().substring(0,document.getDocumentName().lastIndexOf('.')+1) + postfix);
      email.setSubject(email.getSubject().substring(0,email.getSubject().lastIndexOf('.') + 1) + postfix);
      
      String state = docOperationManager.sendDocumentByEmailAttachement(mailForm.getSender(), email, document, version);
      request.setAttribute("state", state);
      
      try{
     	 // add Email Audit Trail Record;

      	DmsEmailAuditTrail dmsEmailAuditTrail = new DmsEmailAuditTrail();
        DmsEmailAuditTrailDAObject emailDAO = new DmsEmailAuditTrailDAObject(sessionCon,conn);
        dmsEmailAuditTrail.setUserid(sessionCon.getUserRecordID());
        dmsEmailAuditTrail.setOperation(EmailAuditTrailConstant.OPERATION_EMAIL_DOCUMENT);
        dmsEmailAuditTrail.setEmailType(EmailAuditTrailConstant.EMAIL_TYPE_OUTBOUND);
        dmsEmailAuditTrail.setEmailFrom(UserInfoFactory.getUserEmailAddress(sessionCon.getUserRecordID()).toString());
        dmsEmailAuditTrail.setEmailTo(mailForm.getRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailCc(mailForm.getCCRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailBcc(mailForm.getBCCRecipients().replaceAll(",",";"));
        dmsEmailAuditTrail.setEmailSubject(mailForm.getSubject());
        dmsEmailAuditTrail.setAttchSource("DMS");
        dmsEmailAuditTrail.setAttchName(locationPath);
        dmsEmailAuditTrail.setSentDate(Utility.getCurrentTimestamp().toString());
        dmsEmailAuditTrail.setAttchCount(new Integer(1));
        dmsEmailAuditTrail.setRecordStatus(GlobalConstant.RECORD_STATUS_ACTIVE);
   	    dmsEmailAuditTrail.setCreatorID(sessionCon.getUserRecordID());
   	    dmsEmailAuditTrail.setCreateDate(Utility.getCurrentTimestamp());
   	    dmsEmailAuditTrail.setUpdateCount(new Integer(0));
   	    dmsEmailAuditTrail.setUpdaterID(sessionCon.getUserRecordID());
   	    dmsEmailAuditTrail.setUpdateDate(Utility.getCurrentTimestamp());
        dmsEmailAuditTrail = (DmsEmailAuditTrail)emailDAO.insertObject(dmsEmailAuditTrail);
        conn.commit();

      }catch(Exception e){
     	  log.error(e);
      }
     
      mailForm.setContactList(mailForm.getContactList());
      mailForm.setContactPersonIDs(mailForm.getContactPersonIDs());
    }catch(ApplicationException appe){
    	throw appe;
    }catch(Exception e){
      log.error(e);
    }finally{
      sessionCon=null;
      docRetrievalManager.release();
      conn = null;
    }

  }
  
  /**
   * get Recepients from contact list.
   * @param mailForm
   * @param request
   * @return
   * @throws ApplicationException
   */
  protected String getExtraRecipients(DmsSendEmailForm mailForm,HttpServletRequest request) throws ApplicationException{
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    StringBuffer extraRecipients=new StringBuffer();

    MtmContactListObjectLinkDAObject mtmContactListObjectLinkDAO=new MtmContactListObjectLinkDAObject(sessionContainer,conn);
    UserRecordDAObject userRecordDAO = new UserRecordDAObject(sessionContainer, conn);
    ContactPersonDAObject contactPersonDAO=new ContactPersonDAObject(sessionContainer,conn);
    
    if(!Utility.isEmpty(mailForm.getContactPersonIDs())){
      for(int i=0;i<mailForm.getContactPersonIDs().length;i++){
        Integer contactPersonID=TextUtility.parseIntegerObj(mailForm.getContactPersonIDs()[i]);
        ContactPerson contactPerson=(ContactPerson)contactPersonDAO.getObjectByID(contactPersonID);
        if(!Utility.isEmpty(contactPerson.getEmail())){
          extraRecipients.append(contactPerson.getEmail()+";");
        }
      }
    }
    if(!Utility.isEmpty(mailForm.getContactList())){
      for(int i=0;i<mailForm.getContactList().length;i++){
        Integer contactListID=TextUtility.parseIntegerObj(mailForm.getContactList()[i]);
        List userList=mtmContactListObjectLinkDAO.getObjectIDListByObjectTypeContactListID(MtmContactListObjectLink.OBJECT_TYPE_USER_RECORD,contactListID);
        List newUserList=new ArrayList();
        for(int j=0;j<userList.size();j++){
          Integer userRecordID=(Integer)userList.get(j);
          newUserList.add(userRecordID.toString());
        }
        List groupList=mtmContactListObjectLinkDAO.getObjectIDListByObjectTypeContactListID(MtmContactListObjectLink.OBJECT_TYPE_USER_GROUP,contactListID);
        List roleList=mtmContactListObjectLinkDAO.getObjectIDListByObjectTypeContactListID(MtmContactListObjectLink.OBJECT_TYPE_USER_ROLE,contactListID);
        List extraUserLsit = userRecordDAO.getIDListByLists(newUserList, groupList, roleList);
        for(int j=0;j<extraUserLsit.size();j++){
          Integer userRecordID=(Integer)extraUserLsit.get(j);
          String userAddress=UserInfoFactory.getUserEmailAddress(userRecordID);
          if(!Utility.isEmpty(userAddress)){
            extraRecipients.append(userAddress+";");
          }
        }
        List contactPersonList=mtmContactListObjectLinkDAO.getObjectIDListByObjectTypeContactListID(MtmContactListObjectLink.OBJECT_TYPE_CONTACT_PERSON,contactListID);
        for(int j=0;j<contactPersonList.size();j++){
          Integer contactPersonID=(Integer)contactPersonList.get(j);
          ContactPerson contactPerson=(ContactPerson)contactPersonDAO.getObjectByID(contactPersonID);
          if(!Utility.isEmpty(contactPerson.getEmail()) && extraRecipients.toString().indexOf(contactPerson.getEmail())<0){
            extraRecipients.append(contactPerson.getEmail()+";");
          }         
        }
      }
    }
    return extraRecipients.toString();   
  }
  
}
